<?php

namespace App\Http\Controllers;

use App\Post;
use Exception;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;

class PostController extends Controller
{

    /**
     * 列表
     * @return Application|Factory|View
     */
    public function index()
    {
        $posts = Post::orderBy("created_at", "desc")->paginate(10);
        return view('post/index', compact('posts'));
    }

    /**
     * 详情
     * @param Post $post
     * @return Application|Factory|View
     */
    public function show(Post $post)
    {
        return view('post/show', compact('post'));

    }

    /**
     * 创建页面
     * @return Application|Factory|View
     */
    public function create()
    {
        return view("post/create");
    }

    /**
     * 创建逻辑
     * @throws ValidationException
     */
    public function store()
    {

        //验证
        $this->validate(request(), [
            'title' => 'required|string|max:100|min:5',
            'content' => 'required|string|min:10',
        ]);
        //逻辑
        $post = Post::create(request(['title', 'content']));
        //渲染
        return redirect("/posts");
    }

    /**
     * 更新页面
     * @param Post $post
     * @return Application|Factory|View
     */
    public function edit(Post $post)
    {
        return view('post/edit', compact('post'));
    }

    /**
     * 更新操作
     * @param Post $post
     * @return Application|RedirectResponse|Redirector
     * @throws ValidationException
     */
    public function update(Post $post)
    {
        //验证
        //验证
        $this->validate(request(), [
            'title' => 'required|string|max:100|min:5',
            'content' => 'required|string|min:10',
        ]);
        //逻辑
        $post->title = request('title');
        $post->content = request('content');
        $post->save();

        //渲染
        return redirect("/posts/{$post->id}");
    }

    /**
     * 删除
     * @param Post $post
     * @return Application|RedirectResponse|Redirector
     * @throws Exception
     */
    public function delete(Post $post)
    {
        //TODO:用户权限验证

        $post->delete();
        return redirect("/posts");
    }

    /**
     * 上传
     * @param Request $request
     * @return string
     */
    public function imageUpload(Request $request)
    {
        $path = $request->file('wangEditorH5File')->storePublicly(md5(time()));
        return asset('storage/' . $path);

    }


}
